package com.shawn.server.controller;

import com.shawn.model.entity.UserInfo;
import com.shawn.server.interceptor.ThreadContext;
import com.shawn.server.service.UserInfoService;
import com.shawn.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;
    /*
    * 登录获取验证码*/
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map<String,Object> map) throws Exception {
        log.info("接收到用户登录PhoneNumber:{}",map.toString());
        //获取手机号
        String phone =(String)map.get("phone");
        //根据手机号获取当前用户对象
        return userService.sendShortMessage(phone);

    }

    @PostMapping("/loginVerification")
    public ResponseEntity loginCheck(@RequestBody Map<String,Object> map){
        log.info("接收到用户登录信息:{}",map.toString());
        //获取手机号,验证码
        String phone =(String)map.get("phone");
        String verificationCode =(String) map.get("verificationCode");
        return userService.loginCheck(phone,verificationCode);
    }

    /**
     * 登录完成信息
     *
     * @param token    令牌
     * @param userInfo 用户信息
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginCompleteInfo(@RequestHeader("Authorization")String token, @RequestBody UserInfo userInfo) throws ParseException {
        log.info("接收到用户完整信息token:{},userInfo:{}",token,userInfo);
        Long userId = ThreadContext.getUserId();
        userInfo.setId(userId);
        //保存用户信息
        userInfoService.saveUserInfo(userInfo);
        return ResponseEntity.ok("用户信息已完善!");
    }

    /**
     * mvc中经过文件解析器转化为MultipartFile对象处理
     * @param headPhoto 头像
     * @return {@link ResponseEntity}
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto) throws IOException {
        //判断token是否安全(篡改,过期)
        //解析token获取用户id
        Long id = ThreadContext.getUserId();

        //调用service根究id保存头像URL
        return userInfoService.updateHeadPhoto(headPhoto, id);
    }
}
